package cn.creditease.std.factory;

import cn.creditease.std.config.JobConsumerConfig;
import cn.creditease.std.context.JobAlloterContext;
import cn.creditease.std.factory.impl.DefaultMQJobAlloterFactoryImpl;
import cn.creditease.std.utils.IpUtils;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * @Description: 分发工厂构造器
 * @Author: kai.yang
 * @Date: 2019-08-13 17:17
 */
public class JobAlloterFactoryBuilder {

    /**
     * 构造mq分发者响应配置工厂
     */

    RabbitTemplate rabbitTemplate;

    ConnectionFactory connectionFactory;



    DataSource dataSource;

    String consumerId = IpUtils.getLocalIp();


    /**
     * 每一个jobGroup的可以单独配置属性，不配置采用默认值
     */
    Map<String, JobConsumerConfig> jobConsumerConfigMap = new HashMap<>();

    /**
     * 构建mq消费工厂
     */
    public JobAlloterFactory buildMqFactory() {
        if (rabbitTemplate == null || connectionFactory == null) {
            throw new IllegalArgumentException("初始化mq分发消费者，rabbitTemplate 、connectionFactory不能为空!");
        }


        DefaultMQJobAlloterFactoryImpl defaultMQJobAlloterFactory = new DefaultMQJobAlloterFactoryImpl(rabbitTemplate,
            connectionFactory);

        JobAlloterContext.init(dataSource, consumerId,jobConsumerConfigMap, defaultMQJobAlloterFactory);

        defaultMQJobAlloterFactory.startLisenter();

        return defaultMQJobAlloterFactory;
    }


    public JobAlloterFactoryBuilder setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        return this;
    }

    public JobAlloterFactoryBuilder setConnectionFactory(
        ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
        return this;
    }

    public JobAlloterFactoryBuilder setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        return this;
    }

    public JobAlloterFactoryBuilder setConsumerId(String consumerTag) {
        this.consumerId = consumerTag;
        return this;
    }

    public JobAlloterFactoryBuilder setJobConsumerConfigMap(
        Map<String, JobConsumerConfig> jobConsumerConfigMap) {
        this.jobConsumerConfigMap = jobConsumerConfigMap;
        return this;
    }
}


